package com.cloudcc.mobile.view.schedule;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.bean.SuccessBean;
import com.mypage.utils.UtilsDate;
import com.mypage.utils.UtilsShowDialog;
import com.mypage.view.activity.AtContaxtActivity_;
import com.mypage.view.datedialog.DateTimeUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class NewTaskActivity extends Activity implements OnClickListener {
	private TextView bar_title_text;
	private Button mBtnBack;// 返回按钮
	private EditText zhutieditText;// 主题
	private Button beifenpeireneditText;// 被分配人
	private Button zhuangtaieditText;// 状态
	private Button xiangguanxiangeditText;// 相关项
	private RelativeLayout dataLayout;// 这是日期时间的点击时间
	private EditText beizhuedit;
	private Button newtaskbtn;
	private Button mTime;
	private int mPerson = 1;
	private int mStateCode = 2;
	private String userId;
	private UtilsShowDialog showDialog;
	private String mGetTime;
	private String mXgx = "";
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private String stateString;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newtask);
		showDialog = new UtilsShowDialog(this);
		bar_title_text = (TextView) findViewById(R.id.bar_title_text);
		if ("en".equals(mEns)) {
			bar_title_text.setText("New Task");
		}else{
			bar_title_text.setText("新建任务");
		}
		
//		Log.d("shijianshisha",getIntent().getStringExtra("clickTime") );
		mGetTime = getIntent().getStringExtra("clickTime");
		mBtnBack = (Button) findViewById(R.id.mBtnBack);// 返回按钮
		zhutieditText = (EditText) findViewById(R.id.zhutieditText);// 主题
		beifenpeireneditText = (Button) findViewById(R.id.beifenpeireneditText);// 被分配人
		zhuangtaieditText = (Button) findViewById(R.id.zhuangtaieditText);// 状态
		xiangguanxiangeditText = (Button) findViewById(R.id.xiangguanxiangeditText);// 相关项
		dataLayout = (RelativeLayout) findViewById(R.id.dataLayout);
		beizhuedit = (EditText) findViewById(R.id.beizhuedit);
		newtaskbtn = (Button) findViewById(R.id.newtaskbtn);
		mTime = (Button) findViewById(R.id.daoqiriqieditText);
        setTimeStr();
		mBtnBack.setOnClickListener(this);
		zhutieditText.setOnClickListener(this);
		beifenpeireneditText.setOnClickListener(this);
		zhuangtaieditText.setOnClickListener(this);
		xiangguanxiangeditText.setOnClickListener(this);
		dataLayout.setOnClickListener(this);
		beizhuedit.setOnClickListener(this);
		newtaskbtn.setOnClickListener(this);
		mTime.setOnClickListener(this);

	}
public void setTimeStr(){
	String me = "自己";
	String mTimes = "未开始";
	if ("en".equals(mEns)) {
		 me = "Own oneself";
		 mTimes = "Has not started";
	}else{
		 me = "自己";
		 mTimes = "未开始";
	}
	userId = RunTimeManager.getInstance().getUserId();
	beifenpeireneditText.setText(me);
	if (mGetTime.equals("")) {
		mTime .setText(UtilsDate.getStringDateShort());
	}else{
		mTime.setText(mGetTime);
		int s = mTime.getText().toString().length();
	}
	zhuangtaieditText.setText(mTimes);
	
}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		// 返回
		case R.id.mBtnBack:
			finish();
			break;
		// 主题
		case R.id.zhutieditText:

			break;
		// 被分配人
		case R.id.beifenpeireneditText:
			setFenPeiActivity();
			break;
		// 状态
		case R.id.zhuangtaieditText:
			setStateActivity();
			break;
		// 相关项
		case R.id.xiangguanxiangeditText:
			setXiangGuanActivity();
			break;
		// 选择时间
		case R.id.dataLayout:
//			final Button daoqiriqieditText = (Button) findViewById(R.id.daoqiriqieditText);// 到期日期
//			// 弹出
//			DateTimeUtil.initSelectTimePopuwindow_s(NewTaskActivity.this,
//					daoqiriqieditText, false);
			break;
		case R.id.daoqiriqieditText:
			final Button daoqiriqieditTexts = (Button) findViewById(R.id.daoqiriqieditText);// 到期日期
			// 弹出
			DateTimeUtil.initSelectTimePopuwindow_s(NewTaskActivity.this,
					daoqiriqieditTexts, false);
			break;
		// 内容
		case R.id.beizhuedit:
			break;
		// 保存
		case R.id.newtaskbtn:
			getContent();
			break;
		default:
			break;
		}
	}

	String mTheme;
	String mFenPeiRen;
	String mDateTime;
	String mState;
	String mXinagGuan;
	String mContent;
	String mJsonData;

	public void getContent() {

		// 主题
		mTheme = zhutieditText.getText().toString().trim();
		// 被分配人名称
		mFenPeiRen = beifenpeireneditText.getText().toString().trim();
		// 被分配人id
		// userId
		// 到期日期
		mDateTime = mTime.getText().toString().trim();
		// 状态
//		mState = zhuangtaieditText.getText().toString().trim();
		mState = stateString;
		// 相关项
//		mXinagGuan = xiangguanxiangeditText.getText().toString().trim();
		// 内容
		mContent = beizhuedit.getText().toString().trim();
		String mThemes = "主题不能为空";
		String mPersons = "被分配人不能为空";
		String mTimesa = "时间不能为空";
		String mStatas = "状态不能为空";
		String mSaves = "正在保存...";
		
		if ("en".equals(mEns)) {
			 mThemes = "The topic can not be empty";
			 mPersons = "The assignee can not be empty";
			 mTimesa = "Time can not be empty";
			 mStatas = "State can not be empty";
			 mSaves = "Saving...";
		}else{
			 mThemes = "主题不能为空";
			 mPersons = "被分配人不能为空";
			 mTimesa = "时间不能为空";
			 mStatas = "状态不能为空";
			 mSaves = "正在保存...";
		}
		
		
		
		
		
		
		
		
		if ("".equals(mTheme)) {
			Toast.makeText(this, mThemes, Toast.LENGTH_SHORT).show();
			return;
		} else if ("".equals(mFenPeiRen)) {
			Toast.makeText(this, mPersons, Toast.LENGTH_SHORT).show();
			return;
		} else if ("".equals(mDateTime)) {
			Toast.makeText(this, mTimesa, Toast.LENGTH_SHORT).show();
			return;
		} else if ("".equals(mState)) {
			Toast.makeText(this, mStatas, Toast.LENGTH_SHORT).show();
		} else {
			// 发送数据
			showDialog.onShowLoadingDialog(mSaves);
			createJson();
		}
	}

	// 把数据转换成json格式。用于上传服务端
	public void createJson() {
		JSONObject object = new JSONObject();

		try {
			object.put("subject", mTheme);
			object.put("belongtoid", userId);
			object.put("name", mTheme);
			object.put("expiredate", mDateTime);
			object.put("status", mState);
			if(mXinagGuan!=null&&mXinagGuan.length()>5){
				object.put("relateid", mXinagGuan);
				object.put("relateobj", mXinagGuan.substring(0, 3));
			}
			object.put("istask", "1");
			object.put("remark", mContent);
			String mChange = "["+object.toString()+"]";
			mJsonData = mChange;
			System.out.println(object);
			// Log.d("/////////////////", object.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sendDataHttp();
	}

	/**
	 * 保存数据(上传到服务端)
	 */
	public void sendDataHttp() {
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
		params.addBodyParameter("serviceName", "insert");
		params.addBodyParameter("objectApiName", "Task");
		params.addBodyParameter("data", mJsonData);
		Log.d("任务url-------------------------", UrlManager.getInterfaceUrl()+"?data="+mJsonData+"&binding"+RunTimeManager.getInstance().getServerBinding()
				+"&serviceName=insert"+"&objectApiName=Task");
		utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showDialog.onDismissLoadingDialog();
				Log.d("保存接口失败-------------------------", arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				showDialog.onDismissLoadingDialog();
				Log.d("保存接口失败-------------------------", arg0.result);
				SuccessBean mSucc = new Gson().fromJson(arg0.result, SuccessBean.class);
				if (mSucc.result) {
					if("en".equals(mEns)){
						Toast.makeText(NewTaskActivity.this, "Save success", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(NewTaskActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
					}
					
					finish();
				}else{
					if("en".equals(mEns)){
						Toast.makeText(NewTaskActivity.this, "Save failed Please try again", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(NewTaskActivity.this, "保存失败 请您重试", Toast.LENGTH_SHORT).show();	
					}
				
				}
			}
		});
	}

	/**
	 * 被分配人
	 */
	public void setFenPeiActivity() {
		Intent intent = new Intent();
		intent.setClass(this, AtContaxtActivity_.class);
		intent.putExtra("bei",66);
		startActivityForResult(intent, mPerson);

	}

	/**
	 * 选择状态
	 */
	public void setStateActivity() {
		Intent intent = new Intent();
		intent.setClass(this, NewStateActivity.class);
		intent.putExtra("m", "t");
		startActivityForResult(intent, mStateCode);
	}

	/**
	 * 相关项
	 */
	public void setXiangGuanActivity() {
		Intent intent = new Intent(this, NewRelatedActivity.class);
		intent.setClass(this, NewRelatedActivity.class);
		startActivityForResult(intent, 9);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(null==data){
			return;
		}
		switch (requestCode) {
		case 1:
			String userName = data.getStringExtra("name");
			if ("".equals(userName)) {
				return;
			}
			beifenpeireneditText.setText(userName);
			userId = data.getStringExtra("userId");
			break;
		case 2:
             String mNames = data.getStringExtra("nameName");
             if ("".equals(mNames)) {
				return;
			}
			stateString = data.getStringExtra("name");
			zhuangtaieditText.setText(mNames);

			break;
		case 9://相关项
			mXinagGuan = data.getStringExtra("AvA");
			String strName =  data.getStringExtra("AvAname");
			if ("".equals(strName)) {
				return;
			}
			xiangguanxiangeditText.setText(strName);
			break;
		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}
